<template>
  <div>
    <div>
      <el-divider content-position="left">角色查询</el-divider>
      <el-form ref="form" :model="form" label-width="80px" class="">
        <el-form-item class="form-item" label="角色名">
          <el-input v-model="form.rname" placeholder="角色名"></el-input>
        </el-form-item>
        <el-form-item class="form-item" label="角色描述">
          <el-input v-model="form.rdesc" placeholder="角色描述"></el-input>
        </el-form-item>
        <el-form-item class="form-item">
          <el-button class="form-btn" type="primary" @click="onQuery">查询</el-button>
          <el-button class="form-btn" @click="clearQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-divider content-position="left">角色列表</el-divider>
    <!--增改删导出-->
    <el-row>
      <el-button class="tag-btn" type="success" plain @click="addItfVisible = true">新增</el-button>
      <el-button class="tag-btn" type="warning" plain @click="modifyItf('modify')">修改</el-button>
      <el-button class="tag-btn" type="danger" plain @click="delItf('del')">删除</el-button>
      <el-button class="tag-btn" type="info" plain @click="outputItfData">导出</el-button>
      <template>
        <el-input-number class="curPageCounter" @change="handleCurrentChange" v-model="curPage" :min="1" :max="pages" label="描述文字"></el-input-number>
      </template>
    </el-row>

    <!--列表-->
    <template>
      <el-table
        class="interface-table"
        ref="multipleTable"
        :data="roletableData"
        tooltip-effect="dark"
        style="width: 100%"
        @selection-change="handleSelectionChange">
        <el-table-column
          align="center"
          type="selection"
          width="55">
        </el-table-column>
        <el-table-column
          align="center"
          prop="roleId"
          label="角色ID"
          width="70">
        </el-table-column>
        <el-table-column
          align="center"
          prop="roleName"
          label="角色名称"
          width="150">
        </el-table-column>
        <el-table-column
          align="center"
          prop="roleDesc"
          label="角色描述"
          width="360">
        </el-table-column>
        <el-table-column
          align="center"
          prop="enabled"
          label="是否启用"
          width="100">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.enabled"
              @change="handleSwithEnable(scope)"
              active-color="#13ce66"
              inactive-color="#ff4949">
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column
          align="center"
          prop="createTime"
          label="创建时间"
          width="150">
        </el-table-column>
        <el-table-column
          align="center"
          prop="updateTime"
          label="更新时间"
          width="200">
        </el-table-column>
        <el-table-column
          align="center"
          label="操作">
          <template slot-scope="scope">
            <el-button
              v-show="scope.row.enabled"
              size="mini"
              icon="el-icon-star-off"
              type="success"
              @click="handleAuthrize(scope.$index, scope.row)">授权</el-button>
            <el-button
              v-show="scope.row.enabled"
              size="mini"
              icon="el-icon-edit"
              type="primary"
              @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
            <el-button
              size="mini"
              type="danger"
              @click="handleDelete(scope.$index, scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div>
        <el-pagination
          background
          class="interpage"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="curPage"
          :page-sizes="[5, 10, 20, 50]"
          :page-size="size"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
        </el-pagination>
      </div>
    </template>
    <!--新增接口对话框-->
    <el-dialog
      title="新增角色"
      :visible.sync="addItfVisible"
      width="40%">
      <el-form label-width="80px">
        <el-form-item label="角色名称">
          <el-input v-model="addItfForm.name" placeholder="请输入角色名称"></el-input>
        </el-form-item>
        <el-form-item label="角色描述">
          <el-input
            style="font-size: 16px;"
            type="textarea"
            :rows="5"
            placeholder='请输入角色描述'
            v-model="addItfForm.desc">
          </el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addItfVisible = false">取 消</el-button>
        <el-button type="primary" @click="addItf">提交</el-button>
      </span>
    </el-dialog>

    <!--修改接口对话框-->
    <el-dialog
      title="修改角色"
      :visible.sync="modifyRoleVisible"
      width="40%">
      <el-form label-width="80px">
        <el-form-item label="角色名称">
          <el-input v-model="modifyRoleForm.name" :placeholder="modifyRoleForm.name" disabled="disabled"></el-input>
        </el-form-item>
        <el-form-item label="接口URL">
          <el-input v-model="modifyRoleForm.desc" :placeholder="modifyRoleForm.desc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="modifyRoleVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitModifyItf">提交</el-button>
      </span>
    </el-dialog>

    <!--资源授权穿梭框-->
    <el-dialog
      title="资源授权"
      :visible.sync="authDivVisial"
      width="50%">
      <div style="margin-left: 10%">
        <div style="margin-top: 10px;margin-bottom: 20px">
          <span style="padding-top: 10px; ">请选择资源类型：</span>
          <el-radio-group v-model="authDivResType" size="medium">
            <el-radio-button label="JK" >接口资源</el-radio-button>
            <el-radio-button label="CD">菜单资源</el-radio-button>
          </el-radio-group>
        </div>
        <div v-show="authDivResType === 'JK'">
          <template>
            <el-transfer
              :titles="['未授权资源', '已授权资源']"
              filterable
              filter-placeholder="请输入资源名称"
              v-model="selfJKResData"
              :render-content="renderFunc"
              @change="handleResChange"
              :data="allJKResData">
            </el-transfer>
          </template>
        </div>
        <div v-show="authDivResType === 'CD'">
          <template>
            <el-transfer
              :titles="['未授权资源', '已授权资源']"
              filterable
              filter-placeholder="请输入资源名称"
              v-model="selfCDResData"
              :render-content="renderFunc"
              @change="handleResChange"
              :data="allCDResData">
            </el-transfer>
          </template>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="authDivVisial = false">确 定</el-button>
      </span>
    </el-dialog>



  </div>
</template>

<script>
  export default {
    name: "role",
    props: {
    },
    data() {
      return {
        /*查询表单*/
        form: {
          rname: '',
          rdesc: ''
        },
        /*接口列表*/
        roletableData: [],
        multipleSelection: [],
        /*分页*/
        curPage: -1,
        size: -1,
        total: 0,
        pages: 0,
        addItfVisible: false,
        addItfForm: {
          name: '',
          desc: '',
        },
        modifyRoleVisible: false,
        modifyRoleForm: {
          name: '',
          desc: '',
        },
        //系统资源列表
        allResData: [],
        allJKResData: [],
        allCDResData: [],
        //当前角色所拥有的资源列表
        selfResData: [],
        selfJKResData: [],
        selfCDResData: [],
        renderFunc(h, option) {
          return <span>{ option.key } - { option.label }</span>;
        },
        //授权按钮初始可见
        authBtnVisial: true,
        //授权DIV可见
        authDivVisial: false,
        authDivResType: 'JK',

        authRoleId: 0
      }
    },
    mounted: function(){
      this.queryRoleItfList();
    },
    computed: {
      headers() {
        return {
          Authentication: this.$store.state.token,
          RefreshToken: this.$store.state.refresh_token
        };
      }
    },
    methods: {
      handleSwithEnable(scope){
        this.$http.post("/role/info/isEnableRole", {
          "roleId": scope.row.roleId,
          "isEnabled": scope.row.enabled
        }).then(resp => {
          if(resp.data.errCode === 200){
            if(scope.row.enabled){
              this.$message.success("角色["+scope.row.roleName+"]已启用");
            }else{
              this.$message.success("角色["+scope.row.roleName+"]已停用");
            }
          }
        })
      },
      resetInterfaceQueryForm(form) {
        this.$refs[form].resetFields();
      },
      //接口查询
      onQuery(){
        this.queryRoleItfList();
        console.log("查询成功！");
      },
      handleSelectionChange(val) {
        this.multipleSelection = val;
      },
      //授权处理
      handleAuthrize(index, row){
        console.log(index, row);
        this.authDivVisial = true;
        this.authRoleId = row.roleId;
        this.authrizeResource(row.roleId);
      },
      handleEdit(index, row) {
        console.log(index, row);
        this.modifyItf(row.roleId);
      },
      handleDelete(index, row) {
        console.log(index, row);
        if(confirm("确认要删除？")){
          this.delItf(row.roleId);
        };
      },
      handleSizeChange(val) {
        console.log(`每页 ${val} 条`);
        this.size = val;
        this.queryItfList();
      },
      handleCurrentChange(val) {
        console.log(`当前页: ${val}`);
        this.curPage = val;
        this.queryRoleItfList();
      },
      //提交新增接口
      addItf(){
        console.log("提交成功！");
        this.$http.post("/role/info/add", {
          "roleName": this.addItfForm.name,
          "roleDesc": this.addItfForm.desc,
        }).then(resp => {
          if(resp.data.errCode === 200){
            this.$message.success("新增成功！");
            this.addItfVisible = false;
            this.queryRoleItfList();
            this.clearAddItfForm();
          }
        });
      },
      //修改按钮(oprNum操作数为1时则为“修改”功能，否则为编辑)
      modifyItf(oprNum){
        //修改
        if(oprNum === 'modify'){
          //判断是否已选择
          if(this.multipleSelection.length !== 1){
            this.$message.error("请选择一条角色数据！");
            return;
          }
          this.modifyRoleVisible = true;
          this.multipleSelection.forEach(t => {
            this.queryOne(t.roleId);
          });
        }else { //编辑
          this.queryOne(oprNum);
        }
      },
      //删除
      delItf(oprNum){
        //删除按钮
        if(oprNum === 'del'){
          //判断是否已选择
          if(this.multipleSelection.length !== 1){
            this.$message.error("请选择一条角色数据！");
            return;
          }
          if(confirm("确认要删除？")){
            this.multipleSelection.forEach(t => {
              this.submitDelItf(t.roleId);
            });
          }
        }else { //操作中的删除
          this.submitDelItf(oprNum);
        }
      },

      //修改接口
      submitModifyItf(){
        this.$http.post("/role/info/mod", {
          "roleName": this.modifyRoleForm.name,
          "roleDesc": this.modifyRoleForm.desc,
        }).then(resp => {
          if(resp.data.errCode === 200){
            this.$message.success("接口修改成功！");
            this.modifyRoleVisible = false;
            this.queryRoleItfList();
          }
        })
      },

      //导出接口数据
      outputItfData(){
        //判断是否已选择
        if(this.multipleSelection.length === 0){
          this.$message.error("请选择一条角色数据！");
          return;
        }
        this.$http({
          method: "post",
          url: "/mock/interface/export",
          data: this.multipleSelection,
          responseType: "blob"
        }).then(resp => {
          let url = window.URL.createObjectURL(new Blob([resp.data])); //创建blob,设置文件类型
          let a = document.createElement('a'); //创建a标签
          a.download = "接口数据表.xls"; //指定文件名
          a.style.display = 'none';
          a.href = url; //创建url
          a.click(); //click事件触发下载
          // URL.revokeObjectURL(a); //释放内存
        });
      },

      //查询接口列表
      queryRoleItfList(){
        this.$http.post("/role/info/query", {
          "roleName": this.form.rname,
          "roleDesc": this.form.rdesc
        }).then(resp => {
          if (resp.data.errCode === 200){
            console.log("query success!");
            this.roletableData = resp.data.data;
            this.total = resp.data.data.length;
          }
        })
      },

      //查询单个接口
      queryOne(id){
        this.$http.post("/role/info/query/"+id).then(resp => {
          if(resp.data.errCode === 200){
            this.modifyRoleVisible = true;
            this.modifyRoleForm.name = resp.data.data.roleName;
            this.modifyRoleForm.desc = resp.data.data.roleDesc;
          }
        })
      },

      //删除单个接口
      submitDelItf(id){
        this.$http.post("/role/info/delete/"+id).then(resp => {
          if(resp.data.errCode === 200){
            this.$message.success("删除成功！");
            this.queryRoleItfList();
          }
        })
      },

      //清空查询条件
      clearQuery(){
        this.form = {
          rname: '',
          rdesc: ''
        }
      },
      clearAddItfForm(){
        this.addItfForm = {
          name: '',
          desc: '',
        }
      },
      checkJsonArray(respParams) {
        if(respParams === '' || respParams === null){
          this.$message.error("请输入正确格式的响应规则！");
          return;
        }

      },
      handleResChange(value, direction, movedKeys) {
        console.log(value, direction, movedKeys);
        const a = this.allResData;
        //授权
        let t = [];
        if(movedKeys.length > 0){
          movedKeys.forEach(function (item, index) {
            var allResDatum = a[item];
            t.push(allResDatum);
          });
          console.log(t);
        }
        //发送后台进行授权/取消授权操作
        this.$http.post("/res/info/changeAuth", {
          "changeAuthList": t,
          "isAuth": "right" === direction,
          "roleId": this.authRoleId
        }).then(resp => {
            if(resp.data.errCode === 200){
              if("right" === direction){
                this.$message.success("您已成功授权！");
              }else {
                this.$message.success("您已成功取消授权！");
              }
            }
          }
        );
      },

      //角色对资源授权
      authrizeResource(id) {
        console.log(id)
        //查询资源列表
        this.queryResourceList(id);
      },

      //查询所有资源列表
      queryResourceList(id){
        this.$http.post("/res/info/queryAuthrizeResource", {
          "roleId": id
        }).then(resp => {
          if (resp.data.errCode === 200){
            if(this.curPage === -1 || this.size === -1){
              let tempJK = [];
              let tempCD = [];
              let temp = [];
              resp.data.data.hasNotAuthrizeResources.forEach(function (item, index) {
                temp.push({
                  resId: item.resId,
                  label: item.resUrl,
                  key: index,
                  // disabled: item.enabled,
                  resType: item.resType
                });
                if(item.resType === 'JK'){
                  tempJK.push({
                    resId: item.resId,
                    label: item.resUrl,
                    key: index,
                    // disabled: item.enabled,
                    resType: item.resType
                  });
                }else if(item.resType === 'CD'){
                  tempCD.push({
                    resId: item.resId,
                    label: item.resUrl,
                    key: index,
                    // disabled: item.enabled,
                    resType: item.resType
                  });
                }
              });
              this.allResData = temp;
              this.allJKResData = tempJK;
              this.allCDResData = tempCD;
            }

            this.tableData = resp.data.data.data;
          }
        })
      },

    }
  }
</script>

<style scoped>
  .form-item{
    margin-left: 20px;
    width: 20%;
    display: inline-block;
  }
  .form-btn{
    position: relative;
    left: -60px;
  }
  .tag-btn{
    margin-left: 20px;
  }
  .interface-table{
    position: relative;
    left: 20px;
    top:10px;
  }
  .interpage{
    margin-top: 20px;
    margin-left: 20px;
    margin-bottom: 20px;
  }
  .curPageCounter{
    float: right;
    right: 40px;
  }
  .authDivClass{
    width: 800px;
    height: 450px;
    font-size: 16px;
    background-color: white;
    position: relative;
    left: 200px;
    top: -350px;
  }
  .authDiv-footer{
    margin-top: 20px;
  }
</style>
